class UserSessionsController < ApplicationController
  before_filter :require_no_user, :only => [:new, :create]
  before_filter :require_user, :only => :destroy

  #Login form
  def new
    @user_session = UserSession.new
    
    #Remeber where the user came from
    session[:login_from] = request.env['HTTP_REFERER'] || root_url
  end

  #Logs the user in
  def create
    @user_session = UserSession.new(params[:user_session])    

    if @user_session.save
      flash[:notice] = "Succesfully logged in."
      session[:edit_mode] = false
      redirect_to session[:login_from]

    #Checks if the account is not activate yet, if not give them to option
    # to resend the activation e-mail
    elsif @user_session.attempted_record && !@user_session.attempted_record.active?
      flash[:notice] = render_to_string(:partial => 'user_sessions/not_active.erb',
                                        :locals => { :user => @user_session.attempted_record } )
      redirect_to :action => :new
    else
      render :action => :new
    end
  end

  #Logs a user out
  def destroy
    #@user_session = UserSession.find
    #@user_session.destroy
    @current_user_session.destroy
    flash[:notice] = "Successfully logged out."
    redirect_to root_url
  end

end
